package it.poste.il.compensatore.dao.impl;

import it.poste.il.compensatore.dao.MessageDao;
import it.poste.il.compensatore.entities.Message;
import it.poste.il.compensatore.utilities.LoadQueriesSQL;

import java.util.List;
import java.util.Properties;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of MessageDao.
 */
public class MessageDaoImpl extends BaseEntityDaoImpl<Message> implements MessageDao {
    public MessageDaoImpl() {
        super(Message.class, "Message");
    }

    LoadQueriesSQL loadQueriesSQL;
    
	public LoadQueriesSQL getLoadQueriesSQL() {
		return loadQueriesSQL;
	}

	public void setLoadQueriesSQL(LoadQueriesSQL loadQueriesSQL) {
		this.loadQueriesSQL = loadQueriesSQL;
	}

	/**
	 * Take id of the operation from message.
	 * @param msg Entity Message.
	 * @return int Id of the operation.
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public int selectOperationId(Message msg) {
		try {
			Properties p = loadQueriesSQL.getProperties();
			String querySQL = p.getProperty("selectMessageOperationId");
			Query query = getEntityManager().createNativeQuery(querySQL, Integer.class).
					setParameter("id", msg.getId()).setParameter("type", msg.getType());
			return (Integer) query.getResultList().get(0);
		} catch (NoResultException e) {
		      return 0;
		}
	}

	/**
	 * Take id of the status from message.
	 * @param msg Entity Message.
	 * @return int Id of the status.
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public int selectStatusId(Message msg) {
		try {
			Properties p = loadQueriesSQL.getProperties();
			String querySQL = p.getProperty("selectMessageStatusId");
			Query query = getEntityManager().createNativeQuery(querySQL, Integer.class).
					setParameter("id", msg.getId()).setParameter("type", msg.getType());
			return (Integer) query.getResultList().get(0);
		} catch (NoResultException e) {
		      return 0;
		}
	}

	/**
	 * List of messages by type.
	 * @param int Type of messages.
	 * @return List List of messages.
	 */
	//preleva tutti gli id dei messaggi che hanno assoiato un annullamento type=1
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public List<Message> loadListByType(int type) {
		Properties p = loadQueriesSQL.getProperties();
		String querySQL = p.getProperty("loadMessageListByType");
		Query query = getEntityManager().createNativeQuery(querySQL, Message.class).
				setParameter("type", type);
		List<Message> msgs = query.getResultList();
		return msgs;
	}
	
}
